using System;
using System.Linq;
using System.Text;
using DevExpress.ExpressApp;
using System.ComponentModel;
using DevExpress.ExpressApp.DC;
using DevExpress.Data.Filtering;
using DevExpress.Persistent.Base;
using System.Collections.Generic;
using DevExpress.ExpressApp.Model;
using DevExpress.Persistent.BaseImpl;
using DevExpress.Persistent.Validation;
using DevExpress.Xpo;
using DevExpress.ExpressApp.ConditionalAppearance;
using DevExpress.ExpressApp.Editors;

namespace DomainComponents.XCRM
{
    public enum OpportunityStatus
    {
        None = 0,
        Won = 1,
        Canceled = 2,
        [DevExpress.Xpo.DisplayName("Out-Sold")]
        OutSold = 3
    }

    public enum OpportunityRating
    {
        Hot = 0,
        Warm = 1,
        Cold = 2
    }

    public class OpportunityValidationRules
    {
        public const string ProbabilityIsBeetwen0And100 = "ProbabilityyIsBeetwen0And100";
    }

    [DomainComponent]
    public interface IOpportunityCustomer : ICustomer
    {
        [BackReferenceProperty("BackRefCustomer")]
        IList<IOpportunity> Opportunities { get; }
    }

    [DomainComponent]
    [NonPersistentDc]
    public interface IOpportunityTarget
    {
        [VisibleInListView(false)]
        IOpportunity SourceOpportunity { get; set; }
    }

    [DomainComponent]
    public interface IOpportunityInvoice : IInvoice, IOpportunityTarget
    {
        [System.ComponentModel.Browsable(false)]
        IOpportunity BackRefOpportunity { get; set; }
    }

    [DomainLogic(typeof(IOpportunityInvoice))]
    public class OpportunityInvoiceLogic
    {
        public static void AfterChange_BackRefOpportunity(IOpportunityInvoice obj)
        {
            obj.SourceOpportunity = obj.BackRefOpportunity;
        }
        public static void AfterChange_SourceOpportunity(IOpportunityInvoice obj)
        {
            obj.BackRefOpportunity = obj.SourceOpportunity;
        }
    }


    [DomainComponent]
    [VisibleInReports]
    [ImageName("BO_Opportunity")]
    [Appearance("Disable IOpportunity by StatusReason", TargetItems = "*", Criteria = "Status != 'None'", Enabled = false)]
    [Appearance("Hide Amount, Discount, DiscountPercent by Empty Criteria", TargetItems = "Amount, Discount, DiscountPercent", Criteria = "", Visibility = ViewItemVisibility.Hide)]
    [Appearance("Enable EstimatedRevenue", TargetItems = "EstimatedRevenue", Criteria = "RevenueIsUserProvided", Enabled = true)]
    [Appearance("Disable EstimatedRevenue", TargetItems = "EstimatedRevenue", Criteria = "!RevenueIsUserProvided", Enabled = false)]
    [XafDisplayName("Opportunity")]
    public interface IOpportunity : ISaleBase
    {
        OpportunityRating Rating { get; set; }

        OpportunityStatus Status { get; set; }

        decimal EstimatedRevenue { get; set; }

        [VisibleInListView(false)]
        decimal ActualRevenue { get; set; }

        [RuleRange(OpportunityValidationRules.ProbabilityIsBeetwen0And100, DefaultContexts.Save, 0, 100)]
        int Probability { get; set; }

        [VisibleInListView(false)]
        DateTime CloseDate { get; set; }

        [VisibleInListView(false)]
        DateTime EstimatedCloseDate { get; set; }

        [BackReferenceProperty("BackRefOpportunity")]
        IList<IOpportunityInvoice> Invoices { get; }

        [ImmediatePostData]
        [VisibleInListView(false)]
        bool RevenueIsUserProvided { get; set; }

        [Action(PredefinedCategory.View, Caption = "Close Opportunity...", AutoCommit = true,
            TargetObjectsCriteria = "Status = 'None'",
            SelectionDependencyType = MethodActionSelectionDependencyType.RequireSingleObject)]
        void Close(CloseOpportunityParameters parameters);

        [System.ComponentModel.Browsable(false)]
        IOpportunityCustomer BackRefCustomer { get; set; }//TODO: duplicated with IInvoce, IOpportunity, IOrder, IQuote
    }


    [DomainLogic(typeof(IOpportunity))]
    public class OpportunityLogic
    {
        public static void AfterChange_RevenueIsUserProvided(IOpportunity opportunity)
        {
            opportunity.UpdateAmount();
        }
        public static void UpdateAmount(IOpportunity opportunity)
        {
            opportunity.Amount = opportunity.DetailAmount;

            if (!opportunity.RevenueIsUserProvided)
            {
                opportunity.EstimatedRevenue = opportunity.Amount;
            }
        }
        public static void AfterChange_BackRefCustomer(IOpportunity saleBase)
        {
            saleBase.PotentialCustomer = saleBase.BackRefCustomer;
        }
        public static void AfterChange_PotentialCustomer(IOpportunity saleBase)
        {
            saleBase.BackRefCustomer = (IOpportunityCustomer)saleBase.PotentialCustomer;
        }
    }

    //[DefaultClassOptions]
    ////[ImageName("BO_Contact")]
    ////[DefaultProperty("DisplayMemberNameForLookupEditorsOfThisType")]
    ////[DefaultListViewOptions(MasterDetailMode.ListViewOnly, false, NewItemRowPosition.None)]
    ////[Persistent("DatabaseTableName")]
    //// Specify more UI options using a declarative approach (http://documentation.devexpress.com/#Xaf/CustomDocument2701).
    //public class IOpportunity : BaseObject
    //{ // Inherit from a different class to provide a custom primary key, concurrency and deletion behavior, etc. (http://documentation.devexpress.com/#Xaf/CustomDocument3146).
    //    public IOpportunity(Session session)
    //        : base(session)
    //    {
    //    }
    //    public override void AfterConstruction()
    //    {
    //        base.AfterConstruction();
    //        // Place your initialization code here (http://documentation.devexpress.com/#Xaf/CustomDocument2834).
    //    }
    //    //private string _PersistentProperty;
    //    //[XafDisplayName("My display name"), ToolTip("My hint message")]
    //    //[ModelDefault("EditMask", "(000)-00"), Index(0), VisibleInListView(false)]
    //    //[Persistent("DatabaseColumnName"), RuleRequiredField(DefaultContexts.Save)]
    //    //public string PersistentProperty {
    //    //    get { return _PersistentProperty; }
    //    //    set { SetPropertyValue("PersistentProperty", ref _PersistentProperty, value); }
    //    //}

    //    //[Action(Caption = "My UI Action", ConfirmationMessage = "Are you sure?", ImageName = "Attention", AutoCommit = true)]
    //    //public void ActionMethod() {
    //    //    // Trigger a custom business logic for the current record in the UI (http://documentation.devexpress.com/#Xaf/CustomDocument2619).
    //    //    this.PersistentProperty = "Paid";
    //    //}
    //}
}
